package com.stony.core.struts.tag;

import java.math.BigDecimal;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.taglib.TagUtils;
import org.apache.struts.taglib.bean.WriteTag;

import com.stony.core.util.CoreUtils;

/**
 * @author bobby.dou
 * 
 */
public class Write2Tag extends WriteTag {

	private String style2;

	public int doStartTag() throws JspException {

		// Look up the requested bean (if necessary)
		if (ignore) {
			if (TagUtils.getInstance().lookup(pageContext, name, scope) == null) {
				return (SKIP_BODY); // Nothing to output
			}
		}

		// Look up the requested property value
		Object value = TagUtils.getInstance().lookup(pageContext, name,
				property, scope);

		if (value == null) {
			return (SKIP_BODY); // Nothing to output
		}

		if (value instanceof Number
				&& new BigDecimal(value.toString()).compareTo(CoreUtils.ZERO) == 0) {
			return (SKIP_BODY); // Nothing to output
		}

		// Convert value to the String with some formatting
		String output = formatValue(value);

		if ("Title".equals(getStyle2())) {
			output = getStyleTitle(output);
		}

		if ("WBR".equals(getStyle2())) {
			output = CoreUtils.getWBR(output);
		}

		if ("WBR20".equals(getStyle2())) {
			output = getWBR20(output);
		}

		// Print this property value to our output writer, suitably filtered
		if (filter) {
			TagUtils.getInstance().write(pageContext,
					TagUtils.getInstance().filter(output));
		} else {
			TagUtils.getInstance().write(pageContext, output);
		}

		// Continue processing this page
		return (SKIP_BODY);

	}

	private String getWBR20(String str) {
		if (StringUtils.isBlank(str))
			return "";

		StringBuffer buff = new StringBuffer();
		char[] chars = str.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			buff.append(chars[i]);
			if (i > 0 && i % 20 == 0)
				buff.append(" ");
		}
		return buff.toString();
	}

	private String getStyleTitle(String str) {
		if (StringUtils.isBlank(str))
			return "";

		StringBuffer buff = new StringBuffer();
		char[] chars = str.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			buff.append(chars[i]);
			buff.append(" ");
		}
		return buff.toString();
	}

	public String getStyle2() {
		return style2;
	}

	public void setStyle2(String style2) {
		this.style2 = style2;
	}

}
